//
//  LMTools.swift
//  LMScreenshotHint
//
//  Created by LaiMing on 2021/4/16.
//

import UIKit


/// 底部tabbar高度
public let lmTabBarH:CGFloat = UIApplication.shared.statusBarFrame.size.height > 20 ? 83 : 49;

/// 屏幕宽度
public let lmScreenWidth:CGFloat = UIScreen.main.bounds.width

/// 屏幕高度
public let lmScreenHeight:CGFloat = UIScreen.main.bounds.height

/// 底部safearea高度
public let lmSafeBottomH:CGFloat = LMTools.isiPhoneXScreen() ? 34 : 0



public class LMTools: NSObject {
    
    
    /// SDK根据图片名获取图片方法
    /// - Parameter name: <#name description#>
    public static func filePathImageNamed(name:String = "") -> UIImage {
        
        guard name.isEmpty == false else {
            return UIImage.init(named: "") ?? UIImage()
        }
        
        var scale:Int = Int(UIScreen.main.scale)
        
        if scale < 2 {
            
            scale = 2
            
        }else if scale > 3 {
            
            scale = 3
        }
        
        
        let path = Bundle.init(for: LMTools.self).path(forResource: "LMImageResource", ofType: "bundle")

        let bundle = Bundle.init(path: path!)
        
        let imageName:String = "\(name)@\(scale)x"
    
        let imageStr = bundle?.path(forResource: imageName, ofType: "png") ?? ""
        
        let image = UIImage.init(contentsOfFile: imageStr)
        
        return image ?? UIImage()
    
    }
    
    
    /// 获取当前显示的控制器
    /// - Returns: <#description#>
    public static func getCurrentController() -> UIViewController? {
        
        var window = UIApplication.shared.keyWindow
          //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
            
            let windows = UIApplication.shared.windows
            
            for  windowTemp in windows{
                
                if windowTemp.windowLevel == UIWindow.Level.normal{
                    
                window = windowTemp
                break
            }
          }
        }
        let vc = window?.rootViewController
        return getTopVC(withCurrentVC: vc)

    }
    
    private static func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
        
        if VC == nil {
            print("🌶： 找不到顶层控制器")
            return nil
        }
        if let presentVC = VC?.presentedViewController {
            //modal出来的 控制器
            return getTopVC(withCurrentVC: presentVC)
        }else if let tabVC = VC as? UITabBarController {
            // tabBar 的跟控制器
            if let selectVC = tabVC.selectedViewController {
                return getTopVC(withCurrentVC: selectVC)
            }
            return nil
        } else if let naiVC = VC as? UINavigationController {
            // 控制器是 nav
            return getTopVC(withCurrentVC:naiVC.visibleViewController)
        } else {
            // 返回顶控制器
            return VC
        }
    }
    
    
    
    /// 获取当前window
    /// - Returns: 窗口
    public static func getCurrentWindow() -> UIWindow {

        if let window:UIWindow = (UIApplication.shared.delegate?.window)! {

            return window

        }else{

            if #available(iOS 13.0, *) {

                let array:Set = UIApplication.shared.connectedScenes

                let windowScene:UIWindowScene = array.first as! UIWindowScene

                //如果是普通App开发，可以使用

//            SceneDelegate * delegate = (SceneDelegate *)windowScene.delegate;

//            UIWindow * mainWindow = delegate.window;

                if let mainWindow:UIWindow = windowScene.value(forKeyPath:"delegate.window") as? UIWindow{

                    return mainWindow

                }else{

                    return UIApplication.shared.windows.first!
                }

            }else{

                return UIApplication.shared.keyWindow!

            }

        }

    }
    

    /// 截取当前屏幕
    /// - Returns: 图片
    public static func getScreenshotImage() -> UIImage {
        
        var imageSize = CGSize.zero
        let screenSize = UIScreen.main.bounds.size
        let orientation = UIApplication.shared.statusBarOrientation
        
        if orientation.isPortrait {
            
            imageSize = screenSize
        } else {
            imageSize = CGSize(width: screenSize.height, height: screenSize.width)
        }
        
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        
        if let context = UIGraphicsGetCurrentContext() {
            
            for window in UIApplication.shared.windows {
                
                context.saveGState()
                context.translateBy(x: window.center.x, y: window.center.y)
                context.concatenate(window.transform)
                context.translateBy(x: -window.bounds.size.width * window.layer.anchorPoint.x, y: -window.bounds.size.height * window.layer.anchorPoint.y)
                
                if orientation == UIInterfaceOrientation.landscapeLeft {
                    context.rotate(by: .pi / 2)
                    context.translateBy(x: 0, y: -imageSize.width)
                } else if orientation == UIInterfaceOrientation.landscapeRight {
                    context.rotate(by: -.pi / 2)
                    context.translateBy(x: -imageSize.height, y: 0)
                } else if orientation == UIInterfaceOrientation.portraitUpsideDown {
                    context.rotate(by: .pi)
                    context.translateBy(x: -imageSize.width, y: -imageSize.height)
                }
                if window.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:))) {
                    window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
                } else {
                    window.layer.render(in: context)
                }
                context.restoreGState()
            }
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        if let image = image {
            return image
        } else {
            return UIImage()
        }
    }
    
    
    
    
    //是否刘海屏
    public static func isiPhoneXScreen() -> Bool {
        
        guard #available(iOS 11.0, *) else {
            return false
        }
        
        let isX = UIApplication.shared.windows[0].safeAreaInsets.bottom > 0
        return isX
    }
}
